using LCL.Tools.Build;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using LCL.LData;
using LCL.CodeHelper;
using LCL.Config;

namespace LCL.Tools.WinFrm
{
    public partial class FrmDbaDoc : BaseFrm
    {
        public FrmDbaDoc()
        {
            InitializeComponent();
            UIFactory.UIFact().BindDataBaseList(this.cmbDBlist);
            this.radioButton3.Checked = true;
            this.lalBarMessage.Text = "";
            this.label1.Text = "当前服务器：" + DbConfig.GetConfig().DbHost;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.cmbDBlist.SelectedItem == null) return;
                AppConfig.GetInstance().DbName = this.cmbDBlist.SelectedItem.ToString();
                if (this.radioButton1.Checked)
                {
                    MessageBox.Show("正在开发中....");
                }
                else if (radioButton2.Checked)
                {
                    MessageBox.Show("正在开发中....");
                }
                else if (this.radioButton3.Checked)
                {
                    Thread thread = new Thread(new ParameterizedThreadStart(Save_HTML1));
                    thread.IsBackground = true;
                    thread.Start();
                }
                else if (this.radioButton4.Checked)
                {
                    //Bootstrap 
                    Thread thread = new Thread(new ParameterizedThreadStart(Save_HTML2));
                    thread.IsBackground = true;
                    thread.Start();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "文档生成失败！(" + ex.Message + ")。\r\n请关闭重试。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            this.button1.Enabled = true;
        }

        private void Save_HTML1(object lineCount)
        {
            StringBuilder html = new StringBuilder();
            StringBuilder html_table = new StringBuilder();
            StringBuilder html_table_colums = new StringBuilder();
            var tables = Utility.GetDbo().GetTables(AppConfig.GetInstance().DbName);
            if (tables != null && tables.Count > 0)
            {
                int tableCount = tables.Count;
                ProgressBarInit(tableCount);
                html_table.Append("<a name='index'>");
                html_table.Append("<h2 style='text-align:center;line-height:50px;'>数据库设计文档</h2>");
                html_table.Append("<div><b>数据库名：" + AppConfig.GetInstance().DbName + "</b></div>");
                html_table.Append("<table class='table' cellspacing='1' cellpadding='0'  border='1' > ");
                html_table.Append("<thead><tr>");
                html_table.Append("<th>序号</th>");
                html_table.Append("<th>表名</th>");
                html_table.Append("<th>说明</th>");
                html_table.Append("</tr></thead>");

                html_table.Append("<tbody>");
                for (int j = 0; j < tableCount; j++)
                {
                    TableModel table = tables[j];
                    var colums = Utility.GetDbo().GetColumnInfoList(AppConfig.GetInstance().DbName, table.TableName);
                    string table_name = table.TableName.ToLower();

                    html_table.Append("<tr>");
                    html_table.AppendFormat("<td style='text-align:center;'>{0}&nbsp;</td>", j);
                    html_table.AppendFormat("<td><a href='#{0}'>{0}</a>&nbsp;</td>", table_name);
                    html_table.AppendFormat("<td>{0}&nbsp;</td>", table.TableNameRemark);
                    html_table.Append("</tr>");

                    #region 过滤整表没有一个字段说明
                    if (this.checkBox1.Checked)
                    {
                        var inf = colums.Where(p => string.IsNullOrWhiteSpace(p.ColumnRemark)).ToList();
                        if (inf.Count == colums.Count)
                        {
                            continue;
                        }
                    }
                    #endregion

                    if (colums != null && colums.Count > 0)
                    {
                        html_table_colums.Append("<div style='margin - top:30px;'>");
                        html_table_colums.Append("<a name='" + table_name + "'></a>");
                        html_table_colums.Append("<b>表名：" + table_name + "</b>");
                        html_table_colums.Append("<a href='#index' style='float:right; margin-top:6px;'>返回目录</a>");
                        html_table_colums.Append("</div>");
                        html_table_colums.Append("<div>说明：" + table.TableNameRemark + "</div>");

                        html_table_colums.Append("<table class='table' cellspacing='1' cellpadding='0'  border='1'>");
                        html_table_colums.Append("<thead><tr>");
                        html_table_colums.Append("<th>序号</th>");
                        html_table_colums.Append("<th>字段名称</th>");
                        html_table_colums.Append("<th>字段说明</th>");
                        html_table_colums.Append("<th>数据类型</th>");
                        html_table_colums.Append("<th>长度</th>");
                        html_table_colums.Append("<th>默认值</th>");
                        html_table_colums.Append("<th>标识</th>");
                        html_table_colums.Append("<th>主键</th>");
                        html_table_colums.Append("<th>允许空</th>");
                        html_table_colums.Append("</tr></thead>");
                        html_table_colums.Append("<tbody>");
                        for (int i = 0; i < colums.Count; i++)
                        {
                            TableColumn column = colums[i];
                            string css = " ";
                            if (i % 2 == 0)
                            {
                                css = " class='odd' ";
                            }
                            html_table_colums.AppendFormat("<tr {0}>", css);
                            html_table_colums.AppendFormat("<td style='text-align:center;'>{0}&nbsp;</td>", i);
                            html_table_colums.AppendFormat("<td>{0}&nbsp;</td>", column.ColumnName);
                            html_table_colums.AppendFormat("<td>{0}&nbsp;</td>", column.ColumnRemark);
                            html_table_colums.AppendFormat("<td>{0}&nbsp;</td>", column.ColumnType);
                            html_table_colums.AppendFormat("<td>{0}&nbsp;</td>", column.MaxLength);
                            html_table_colums.AppendFormat("<td>{0}&nbsp;</td>", column.DefaultValue);
                            html_table_colums.AppendFormat("<td>{0}&nbsp;</td>", column.IsIdentity ? "√" : "O");
                            html_table_colums.AppendFormat("<td>{0}&nbsp;</td>", column.IsPrimaryKey ? "√" : "O");
                            html_table_colums.AppendFormat("<td>{0}&nbsp;</td>", column.IsNullable ? "√" : "O");
                            html_table_colums.AppendFormat("</tr>");
                        }
                        html_table_colums.Append("</tbody></table>");
                    }

                    ProgressBarStep(j);
                    Application.DoEvents();
                }
                ProgressBarFinish(tableCount);
            }
            string value = "";
            string path = Application.StartupPath + "\\Template\\table.htm";
            if (File.Exists(path))
            {
                html_table.Append("</tbody></table>");
                html_table.Append("</a>");
                html.Append(html_table.ToString());
                html.Append(html_table_colums.ToString());

                using (StreamReader streamReader = new StreamReader(path, Encoding.Default))
                {
                    value = streamReader.ReadToEnd().Replace("<$$tablestruct$$>", html.ToString());
                    streamReader.Close();
                }
                CodeCommon.CreateFiles(CodeCommon.DesktopDirectory + AppConfig.GetInstance().DbName + ".htm", value);
            }
            MessageShow();
        }

        private void Save_HTML2(object lineCount)
        {
            StringBuilder html = new StringBuilder();
            StringBuilder html_table = new StringBuilder();
            StringBuilder html_table_li = new StringBuilder();
            var tables = Utility.GetDbo().GetTables(AppConfig.GetInstance().DbName);
            if (tables != null && tables.Count > 0)
            {
                int tableCount = tables.Count;
                ProgressBarInit(tableCount);
                for (int j = 0; j < tableCount; j++)
                {
                    TableModel table = tables[j];

                    string table_name = table.TableName.ToLower();

                    var colums = Utility.GetDbo().GetColumnInfoList(AppConfig.GetInstance().DbName, table.TableName);

                    if (this.checkBox1.Checked)
                    {
                        var inf = colums.Where(p => string.IsNullOrWhiteSpace(p.ColumnRemark)).ToList();
                        if (inf.Count == colums.Count)
                        {
                            continue;
                        }
                    }

                    if (colums != null && colums.Count > 0)
                    {
                        html_table_li.Append("<li><a href='#" + table_name + "'>" + table_name + table.TableNameRemark + "</a></li>");
                        html_table.Append("<div class='bs-docs-section' id='" + table_name + "'><table  class='table table-condensed table-hover table-striped tablesorter table-fixed table-selectable'>");
                        html_table.AppendFormat("<caption>{0}（{1}）</caption>", table_name, table.TableNameRemark);

                        html_table.Append("<thead><tr>");
                        html_table.Append("<th>字段名称</th>");
                        html_table.Append("<th>字段说明</th>");
                        html_table.Append("<th>数据类型</th>");
                        html_table.Append("<th>长度</th>");
                        html_table.Append("<th>默认值</th>");
                        html_table.Append("<th>标识</th>");
                        html_table.Append("<th>主键</th>");
                        html_table.Append("<th>允许空</th>");
                        html_table.Append("</tr></thead>");
                        html_table.Append(" <tbody>");
                        for (int i = 0; i < colums.Count; i++)
                        {
                            TableColumn column = colums[i];
                            string css = " ";
                            if (i % 2 == 0)
                            {
                                css = " class='odd'";
                            }
                            html_table.AppendFormat("<tr {0}>", css);
                            html_table.AppendFormat("<td>{0}&nbsp;</td>", column.ColumnName.ToLower());
                            html_table.AppendFormat("<td>{0}&nbsp;</td>", column.ColumnRemark);
                            html_table.AppendFormat("<td>{0}&nbsp;</td>", column.ColumnType.ToLower());
                            html_table.AppendFormat("<td>{0}&nbsp;</td>", column.MaxLength);
                            html_table.AppendFormat("<td>{0}&nbsp;</td>", column.DefaultValue);
                            html_table.AppendFormat("<td>{0}&nbsp;</td>", column.IsIdentity ? "√" : "O");
                            html_table.AppendFormat("<td>{0}&nbsp;</td>", column.IsPrimaryKey ? "√" : "O");
                            html_table.AppendFormat("<td>{0}&nbsp;</td>", column.IsNullable ? "√" : "O");
                            html_table.AppendFormat("</tr>");
                        }
                        html_table.Append("</tbody>");
                        html_table.Append("</table></div>");
                    }

                    ProgressBarStep(j);
                    Application.DoEvents();
                }
                ProgressBarFinish(tableCount);
            }
            string path = Application.StartupPath + "\\Template\\table2.htm";
            if (File.Exists(path))
            {
                string value = "";
                using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
                {
                    value = streamReader.ReadToEnd().Replace("<$$tablestruct$$>", html_table.ToString());
                    value = value.Replace("<$$nav$$>", html_table_li.ToString());
                    value = value.Replace("<$$dbName$$>", AppConfig.GetInstance().DbName);
                    value = value.Replace("<$$tableCount$$>", tables.Count.ToString());

                    streamReader.Close();
                }
                CodeCommon.CreateFiles(CodeCommon.DesktopDirectory + AppConfig.GetInstance().DbName + ".htm", value);
            }
            MessageShow();
        }

        delegate void AsynUpdateUI(int step);
        //进度条 初始化
        private void ProgressBarInit(int tableCount)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new AsynUpdateUI(delegate (int s)
                {
                    this.button1.Enabled = false;
                    this.progressBar1.Maximum = tableCount;
                    this.lalBarMessage.Text = this.progressBar1.Value.ToString() + "/" + this.progressBar1.Maximum.ToString();
                }), 0);
            }
        }
        //进度条 进度
        private void ProgressBarStep(int j)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new AsynUpdateUI(delegate (int s)
                {
                    try
                    {
                        this.progressBar1.Value += s;
                        this.lalBarMessage.Text = this.progressBar1.Value.ToString() + "/" + this.progressBar1.Maximum.ToString();
                    }
                    catch
                    {

                    }
                }), j);
            }
        }
        //进度条 完成
        private void ProgressBarFinish(int tableCount)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new AsynUpdateUI(delegate (int s)
                {
                    this.progressBar1.Maximum = tableCount;
                    this.progressBar1.Value = 0;
                    this.lalBarMessage.Text = 0 + "/" + tableCount;
                    this.button1.Enabled = true;
                }), 0);
            }
        }
        private void MessageShow()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new AsynUpdateUI(delegate (int s)
                {
                    MessageBox.Show(this, "文档生成成功！", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }), 0);
            }
        }

    }
}



